<?php
class Groups extends MY_Controller
{
	function __construct()
	{
		parent::__construct();
		
		$this->load->model('group_model');

		$this->validation->set_fields($this->group_model->fields);

		$this->data['leftMenu'] = 'admins/_menu';
	}
	
	function index()
	{
		$this->data['query'] = $this->db->get($this->group_model->table);
		$this->renderLayout();
	}

	function create()
	{
		if (count($_POST))
		{
			$rules = array('group_name', 'group_desc', 'group_order', 'group_status');
			$this->validation->set_rules($this->group_model->getRules($rules));

			if ($this->validation->run() === TRUE)
			{
				$item['group_name'] = $this->validation->group_name;
				$item['group_desc'] = $this->validation->group_desc;
				$item['group_order'] = $this->validation->group_order;
				$item['group_status'] = $this->validation->group_status;
				$item['group_created'] = MYSQL_NOW();
				
				$this->group_model->insert($item);

				redirect('groups/index');
			}
		}
		else
		{
			$this->validation->group_order = 100;
		}
		
		$this->renderLayout();
	}
	
	function delete($id = null)
	{
		$this->group_model->delete($id);

		redirect('groups/index');
	}
	
	function edit($id = null)
	{
		//does the object exist?
		if (!empty($id))
		{
			$object = $this->group_model->get($id);
			
			if (!count($object))
			{
				$this->data['view'] = '_elements/query_no_object';
				$this->load->view($this->data['layout'], $this->data);

				return false; 
			}
		}
		
		if (!count($_POST))
		{
			$this->validation->group_ID = $object['group_ID']; 
			$this->validation->group_name = $object['group_name']; 
			$this->validation->group_desc = $object['group_desc']; 
			$this->validation->group_order = $object['group_order']; 
			$this->validation->group_status = $object['group_status']; 
		}
		else
		{
			$rules = array('group_name', 'group_desc', 'group_order', 'group_status');
			$this->validation->set_rules($this->group_model->getRules($rules));

			if ($this->validation->run() === TRUE)
			{
				$item['group_ID'] = $this->validation->group_ID;
				$item['group_name'] = $this->validation->group_name;
				$item['group_desc'] = $this->validation->group_desc;
				$item['group_order'] = $this->validation->group_order;
				$item['group_status'] = $this->validation->group_status;
				
				$this->group_model->update($item);
				
				redirect('groups/index');
			}
		}
		
		$this->renderLayout();
	}
}
?>